import { defineStore } from 'pinia'
import { saveData, loadData, makeSnapshot } from './db'

export const useAppStore = defineStore('app', {
  state: () => ({
    widgets: [] as any[],
    plugins: [] as any[],
    userPrefs: {} as any
  }),
  actions: {
    /** 启动时从本地加载全部数据 */
    async init() {
      this.widgets = await loadData('widgets')
      this.plugins = await loadData('plugins')
      this.userPrefs = await loadData('userPrefs')
    },
    /** 新增或更新组件并持久化 */
    async upsertWidget(widget: any) {
      await saveData('widgets', widget)
      this.widgets = await loadData('widgets')
      await makeSnapshot('组件变更快照')
    },
    /** 删除组件 */
    async removeWidget(id: string) {
      const { deleteData } = await import('./db')
      await deleteData('widgets', id)
      this.widgets = await loadData('widgets')
      await makeSnapshot('组件删除快照')
    },
    /** 新增或更新插件 */
    async upsertPlugin(plugin: any) {
      await saveData('plugins', plugin)
      this.plugins = await loadData('plugins')
      await makeSnapshot('插件变更快照')
    },
    /** 设置用户偏好 */
    async setUserPrefs(prefs: any) {
      await saveData('userPrefs', { key: 'userPrefs', value: prefs })
      this.userPrefs = prefs
      await makeSnapshot('用户偏好快照')
    }
  }
})
